<?php
namespace app\erp_meixingtiyu\model;

use think\Model;
use think\model\concern\SoftDelete;
use app\erp_meixingtiyu\model\TimeTemplate as TimeTemplateModel;

class TimeFragment extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $table = 'athlon_time_fragment';
    protected $pk = 'time_fragment_id';

    public function parts()
    {
        return $this->belongsToMany(
            ArenaPart::class,
            ArenaPartTimeFragment::class
        );
    }

    public function booked()
    {
        return $this->hasManyThrough(
            Booking::class,
            ArenaPartTimeFragment::class
        );
    }

    public static function getFragmentByTemplateId($timeTemplateId)
    {
        return self::where('time_template_id', $timeTemplateId)
            ->order('sort asc')
            ->paginate(15);
    }

    public function addFragment($params)
    {
        $this->transaction(function () use ($params) {
            // 新增时段
            $fragment = self::create($params);
            // 找到使用该模板的所有场地下的所有半场id
            $template = TimeTemplateModel::find($params['time_template_id']);
            $parts = $template->parts;
            // 关联所有使用该模板的半场
            foreach ($parts as $part) {
                $part->fragments()->save($fragment->time_fragment_id, [
                    'status' => $template->status,
                    'price' => $template->price,
                ]);
            }
        });
    }

    public function deleteFragment($fragmentId)
    {
        $this->transaction(function () use ($fragmentId) {
            $fragment = self::find($fragmentId);
            // 获取所有关联的半场id
            $parts_id = [];
            foreach ($fragment->parts as $part) {
                $parts_id[] = $part->arena_part_id;
            }
            // 删除所有与该时段的关联
            $fragment->parts()->detach($parts_id);
            $fragment->delete();
        });
    }
}
